package club.janna.jrpc.remoting.netty;

import club.janna.jrpc.annotation.SPIService;
import club.janna.jrpc.remoting.Channel;
import club.janna.jrpc.remoting.Client;
import club.janna.jrpc.remoting.Codec;
import club.janna.jrpc.remoting.Handler;
import io.netty.bootstrap.Bootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.LengthFieldBasedFrameDecoder;
import lombok.extern.slf4j.Slf4j;

import java.net.URI;

/**
 * @author Panbo.Guo
 */
@Slf4j
@SPIService("netty")
public class NettyClient implements Client {
    @Override
    public Channel connect(URI uri, Codec codec, Handler handler) {
        String host = uri.getHost();
        int port = uri.getPort();

        Bootstrap bootstrap = new Bootstrap();
        bootstrap.group(new NioEventLoopGroup(1))
                .channel(NioSocketChannel.class)
                .handler(new ChannelInitializer<NioSocketChannel>() {
                    @Override
                    protected void initChannel(NioSocketChannel channel) throws Exception {
                        channel.pipeline().addLast(new FrameEncoder());
                        /**
                         * Frame Decoder
                         * BEFORE DECODE                                     AFTER DECODE
                         * +----------+--------------+----------------+      +----------------+
                         * | Header 1 |  Length      | Actual Content |----->| Actual Content |
                         * |  0xCAFE  | 0x0000000C   | "HELLO, WORLD" |      | "HELLO, WORLD" |
                         * +----------+------------ -+----------------+      +----------------+
                         */
                        channel.pipeline().addLast(new LengthFieldBasedFrameDecoder(10240,
                                2, 4, 0, 6));
                        channel.pipeline().addLast(new NettyCodec(codec));
                        channel.pipeline().addLast(new NettyClientHandler(handler));
                    }
                });
        Channel channel = null;
        try {
            ChannelFuture channelFuture = bootstrap.connect(host, port).sync();
            io.netty.channel.Channel nettyChannel = channelFuture.channel();
            channel = new NettyChannel(nettyChannel);
            channelFuture.addListener(future -> {
                if (!future.isSuccess()) {
                    log.error("连接服务器失败，host -> {}, port -> {}", host, port);
                    throw new RuntimeException("连接服务器失败");
                }
                log.info("已连接到服务器，host -> {}, port -> {}", host, port);
            });
            nettyChannel.closeFuture().addListener(future -> {
               if(!future.isSuccess()) {
                   log.error("断开连接失败，host -> {}, port -> {}", host, port);
                   throw new RuntimeException("断开连接失败");
               }
               log.info("已断开连接，host -> {}, port -> {}", host, port);
            });
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        return channel;
    }
}
